/*
 * Copyright 2015 MingxingWang

 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 *     http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.audaque.graphdb

import scala.collection.mutable

/**
 * Created by Ming on 2015/3/26.
 */
class Schema(val id: Long,
             val fields: Array[(String, Type)]) extends Serializable {

  val size: Int = if (fields == null) 0 else fields.length

  def getFieldNames: Array[String] = if (fields == null) Array[String]() else fields.map(_._1)

  def getFieldTypes: Array[Type] = if (fields == null) Array[Type]() else fields.map(_._2)

  private val f2i: mutable.Map[String, Int] = {
    if (fields == null) {
      mutable.Map[String, Int]()
    } else {
      val map = new mutable.HashMap[String, Int]()
      for (i <- 0 until fields.length)
        map += (fields(i)._1.toLowerCase -> i)
      map
    }
  }

  def getFieldIndex(fieldName: String): Int = {
    if (fieldName == null || fieldName.isEmpty) return -1
    f2i.get(fieldName.toLowerCase) match {
      case Some(index) => index
      case None => -1
    }
  }

  def getFieldName(index: Int): String = {
    if (index < 0 || index >= size) {
      println("Warning, index out of rand in getFieldName [0," + size + "]: " + index)
      ""
    }
    else fields(index)._1
  }

  def getFieldType(index: Int): Type = {
    if (index < 0 || index >= size) {
      println("Warning, index out of rand in getFieldType [0," + size + "]: " + index)
      Type.UnKnown
    } else fields(index)._2
  }

  def getFieldType(fieldName: String): Type = {
    val index = getFieldIndex(fieldName)
    if (index >= 0) {
      getFieldType(index)
    } else {
      Type.UnKnown
    }
  }
  override def toString(): String = {
    val sb = new mutable.StringBuilder()
    sb.append(id).append(" ")
    if(fields == null){
      sb.append("null")
    }else{
      fields.foreach(x => sb.append(x._1).append(":").append(x._2.tid).append(","))
    }
    sb.toString()
  }
}
